package cn.edu.uestc.service;

import cn.edu.uestc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class SignupService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    HttpServletRequest request;

    public boolean signup(User user) {
        String username = user.getUsername();
        Query query = new Query(Criteria.where("username").is(username));
        User userDB = mongoTemplate.findOne(query, User.class, "users");
        if (userDB != null) {
            return false;
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("username", user.getUsername());
            session.setAttribute("user_type", user.getType());
            mongoTemplate.insert(user);
            return true;
        }
    }

    public List<String> getAllOperators() {
        Query query = new Query(Criteria.where("type").is(2));
        List<User> userList = mongoTemplate.find(query, User.class, "users");
        List<String> operators = new ArrayList<>();
        for (User user : userList) {
            operators.add(user.getUsername());
        }
        return operators;
    }
}
